import 'dart:convert';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_html/enough_mail_html.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:signals/signals_core_extended.dart';
import 'email_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

class EmailService {
  // POP3配置
  static String? _username;
  static String? _password;
  static String? _popServer;
  static int? _popPort;
  static bool? _isPopSecure;

  // 设置邮箱配置
  static void setConfig({
    required String username,
    required String password,
    required String popServer,
    required int popPort,
    required bool isPopSecure,
  }) {
    _username = username;
    _password = password;
    _popServer = popServer;
    _popPort = popPort;
    _isPopSecure = isPopSecure;
  }

  // 从SharedPreferences加载配置
  static Future<bool> loadConfig() async {
    final prefs = await SharedPreferences.getInstance();
    _username = prefs.getString('email');
    _password = prefs.getString('password');
    _popServer = prefs.getString('popServer');
    _popPort = int.tryParse(prefs.getString('popPort') ?? '995');
    _isPopSecure = prefs.getBool('isSecure') ?? true;

    return _username != null &&
        _password != null &&
        _popServer != null &&
        _popPort != null;
  }

  // 测试连接
  static Future<void> testConnection() async {
    if (_username == null ||
        _password == null ||
        _popServer == null ||
        _popPort == null) {
      throw Exception('邮箱配置不完整');
    }

    final client = PopClient(isLogEnabled: false);
    try {
      await client.connectToServer(
        _popServer!,
        _popPort!,
        isSecure: _isPopSecure!,
      );
      await client.login(_username!, _password!);
      await client.quit();
    } finally {
      client.disconnect();
    }
  }

  static String generateHtml(MimeMessage mimeMessage) {
    return mimeMessage.transformToHtml(
      blockExternalImages: false,
      emptyMessageText: 'Nothing here, move on!',
    );
  }

  // 获取邮件列表
  static Future<List<Email>> fetchEmails({
    int page = 1,
    int limit = 20,
    String? searchQuery,
  }) async {
    // 检查配置
    if (_username == null ||
        _password == null ||
        _popServer == null ||
        _popPort == null) {
      final configLoaded = await loadConfig();
      if (!configLoaded) {
        throw Exception('邮箱未配置，请先登录');
      }
    }

    final client = PopClient(isLogEnabled: false);
    try {
      await client.connectToServer(
        _popServer!,
        _popPort!,
        isSecure: _isPopSecure!,
      );
      await client.login(_username!, _password!);

      // 获取邮件数量
      final status = await client.status();
      final messageCount = status.numberOfMessages;

      if (messageCount == 0) {
        return [];
      }

      // 计算要获取的邮件范围
      final startIndex = messageCount - (page * limit);
      final endIndex = messageCount - ((page - 1) * limit);

      // 确保索引在有效范围内
      final validStartIndex = startIndex < 0 ? 1 : startIndex + 1;
      final validEndIndex = endIndex > messageCount ? messageCount : endIndex;

      if (validStartIndex > validEndIndex) {
        return [];
      }

      final emails = <Email>[];

      // 获取邮件
      for (int i = validEndIndex; i >= validStartIndex; i--) {
        try {
          final retrieveResult = await client.retrieve(i);

          var x = retrieveResult.mimeData!.decodeBinary('utf-8');
          var mimeMessage = MimeMessage.parseFromData(x);
          // 解析发件人
          final from = '';
          final sender = '';
          final senderEmail = '';

          // 解析主题
          final subject = '';

          var body = generateHtml(mimeMessage);
          // else if (mimeMessage.isTextHtmlMessage()) {
          //   body = mimeMessage.decodeTextHtmlPart() ?? '';
          //   // 简单去除HTML标签
          //   body = body.replaceAll(RegExp(r'<[^>]*>'), '');
          // }

          // 解析附件
          final attachments = <Attachment>[];
          for (final part in mimeMessage.allPartsFlat) {
            // if (part.isAttachment) {
            //   attachments.add(
            //     Attachment(
            //       name: part.decodeFileName() ?? '未知文件',
            //       type: part.mediaType?.text ?? 'application/octet-stream',
            //       size: part.size,
            //       url: null,
            //     ),
            //   );
            // }
          }

          emails.add(
            Email(
              id: i.toString(),
              subject: subject,
              sender: sender,
              senderEmail: senderEmail,
              body: body,
              date: mimeMessage.decodeDate() ?? DateTime.now(),
              isRead: true,
              // POP3不支持已读状态，默认为已读
              attachments: attachments.isEmpty ? null : attachments,
            ),
          );
        } catch (e) {
          debugPrint('获取邮件 $i 时出错: $e');
          // 继续获取下一封邮件
        }
      }

      await client.quit();
      return emails;
    } catch (e) {
      debugPrint('获取邮件列表时出错: $e');
      rethrow;
    } finally {
      client.disconnect();
    }
  }

  // 标记邮件为已读 (POP3不支持，保留此方法以兼容现有代码)
  static Future<bool> markAsRead(String emailId) async {
    // POP3不支持标记已读
    return true;
  }

  // 删除邮件
  static Future<bool> deleteEmail(String emailId) async {
    if (_username == null ||
        _password == null ||
        _popServer == null ||
        _popPort == null) {
      final configLoaded = await loadConfig();
      if (!configLoaded) {
        throw Exception('邮箱未配置，请先登录');
      }
    }

    final client = PopClient(isLogEnabled: false);
    try {
      await client.connectToServer(
        _popServer!,
        _popPort!,
        isSecure: _isPopSecure!,
      );
      await client.login(_username!, _password!);

      // 将邮件ID转换为整数
      final messageId = int.parse(emailId);

      // 标记邮件为删除
      await client.delete(messageId);

      // 提交删除操作
      await client.quit();

      return true;
    } catch (e) {
      debugPrint('删除邮件时出错: $e');
      return false;
    } finally {
      client.disconnect();
    }
  }
}
